package com.twu.biblioteca.menu;

import com.twu.biblioteca.BibliotecaApp;
import com.twu.biblioteca.model.User;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;

/**
 * Created with IntelliJ IDEA.
 * User: Aaron Edwards
 * Date: 10/10/13
 * Time: 11:49 AM
 * Email: aedwards@thoughtworks.com
 */
public class LoginMenuItem implements IMenuItem {
    @Override
    public String getMenuTitleForUser(User currentUser) {
        if (currentUser == null) {
            return "Login";
        } else {
            return "Logout";
        }
    }

    @Override
    public void doAction(BibliotecaApp bibliotecaApp) {
        User currentUser = bibliotecaApp.getCurrentUser();

        PrintStream outputStream = bibliotecaApp.getOutputStream();
        BufferedReader bufferedReader = null;

        try {
            if (currentUser == null) {
                bufferedReader = new BufferedReader(new InputStreamReader(bibliotecaApp.getInputStream()));
                outputStream.print("Username: ");
                String username = bufferedReader.readLine();

                outputStream.print("Password: ");
                String password = bufferedReader.readLine();

                if (bibliotecaApp.logInUser(username, password)) {
                    outputStream.println("Logged in as " + username);
                } else {
                    outputStream.println("Invalid username or password");
                }

            } else { //User is logged in
                outputStream.println("Logged out from user " + currentUser);
                bibliotecaApp.logout();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
